﻿Public Class frm_main

    Private _ftp_client As New FTP.FTP.FtpClient
    Private _list_ftp_server As New List(Of ConnectionInfo)
    Private _tools As New Tools
    Private _ftp_server As New ConnectionInfo



    Private Sub frm_main_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

        Try
            _ftp_client.Dispose()
            Application.Exit()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub _ftp_client_open_async_event(sender As Object, e As FTP.FTP.OpenAsyncCompletedEventArgs)

        Try

            If Not e Is Nothing Then

                If Not String.IsNullOrEmpty(_ftp_server.GetSetPath) Then
                    _ftp_client.ChangeDirectory(_ftp_server.GetSetPath)
                    bgw_get_dir_list.RunWorkerAsync(_ftp_server.GetSetPath)
                Else
                    bgw_get_dir_list.RunWorkerAsync(_ftp_client.CurrentDirectory)
                End If

            Else
                MessageBox.Show(e.Error.Message.ToString, "Fehler beim verbinden!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                UpdateFTPLog("Fehler beim verbinden!", Enums.ResponseType.Client)
            End If

        Catch ex As Exception

            If ex.Message.StartsWith("Could not change working directory") Then
                bgw_get_dir_list.RunWorkerAsync("\")
            Else
                MessageBox.Show(ex.Message, "Fehler beim verbinden!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                UpdateFTPLog("Fehler beim verbinden!", Enums.ResponseType.Client)
            End If

        Finally
            'Lock Control while connecting
            tree_ftp_server.Enabled = True
            QuickConnectToolStripMenuItem.Enabled = True
        End Try


    End Sub


#Region "Invokes"

    Private Sub UpdateFTPLog(ByVal value As String, ByVal _response_type As Enums.ResponseType)
        If Me.InvokeRequired Then
            Me.Invoke(Sub() Me.UpdateFTPLog(value, _response_type))
        Else



            Select Case _response_type

                Case Enums.ResponseType.Client

                    Dim _index = rtb_log.Text.Length

                    rtb_log.AppendText(value & vbNewLine)

                    rtb_log.SelectionStart = _index
                    rtb_log.SelectionLength = rtb_log.Text.Length - (value.Length)
                    rtb_log.SelectionColor = Color.Blue

                Case Enums.ResponseType.Server

                    Dim _index = rtb_log.Text.Length

                    rtb_log.AppendText(value & vbNewLine)

                    rtb_log.SelectionStart = _index
                    rtb_log.SelectionLength = rtb_log.Text.Length - (value.Length)
                    rtb_log.SelectionColor = Color.Green


            End Select

            rtb_log.SelectionStart = rtb_log.Text.Length
            rtb_log.ScrollToCaret()

        End If
    End Sub

    Private Sub ClearFTPItemList()
        If Me.InvokeRequired Then
            Me.Invoke(Sub() Me.ClearFTPItemList())
        Else
            lv_ftp_server_items.Items.Clear()
        End If
    End Sub

    Private Sub UpdateCurrentFTPDir(ByVal value As String)
        If Me.InvokeRequired Then
            Me.Invoke(Sub() Me.UpdateCurrentFTPDir(value))
        Else
            txt_current_ftp_path.Text = value
        End If
    End Sub

    Private Sub AddListViewItem(ByVal value As ListViewItem)
        If Me.InvokeRequired Then
            Me.Invoke(Sub() Me.AddListViewItem(value))
        Else
            lv_ftp_server_items.Items.Add(value)
        End If
    End Sub

#End Region

    Private Sub frm_main_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        If IO.Directory.Exists(IO.Path.Combine(Application.StartupPath, "FTPServer")) = False Then
            IO.Directory.CreateDirectory(IO.Path.Combine(Application.StartupPath, "FTPServer"))
        End If

        UpdateFTPServers()


    End Sub

    Sub UpdateFTPServers()

        tree_ftp_server.Nodes.Clear()

        tree_ftp_server.Nodes.Add("FTP Server")

        For Each _file In IO.Directory.GetFiles(IO.Path.Combine(Application.StartupPath, "FTPServer"), "*.xml")

            Try

                Dim _ftp_server As New ConnectionInfo

                _ftp_server = _tools.XMLDeSerialize(_ftp_server, _file.ToString)

                tree_ftp_server.Nodes(0).Nodes.Add(_ftp_server.GetSetName)

            Catch ex As Exception
                'Catch Silent
            End Try

        Next

    End Sub

    Private Sub FTPServerHinzufügenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FTPServerHinzufügenToolStripMenuItem.Click
        AddHandler frm_ftp_server.UpdateFTPServers, AddressOf UpdateFTPServersEvent
        frm_ftp_server.ShowDialog()
        RemoveHandler frm_ftp_server.UpdateFTPServers, AddressOf UpdateFTPServersEvent
        frm_ftp_server.Dispose()
    End Sub

    Private Sub UpdateFTPServersEvent()
        UpdateFTPServers()
    End Sub

    Private Sub BeendenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BeendenToolStripMenuItem.Click
        _ftp_client.Dispose()
        Application.Exit()
    End Sub

    Private Sub FTPServerLöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FTPServerLöschenToolStripMenuItem.Click, LöschenToolStripMenuItem.Click

        If Not tree_ftp_server.TopNode.Text = tree_ftp_server.SelectedNode.Text Then

            If MessageBox.Show("Wirklich löschen?", "Löschen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                Dim _filname As String

                _filname = IO.Path.Combine(Application.StartupPath, "FTPServer" & IO.Path.DirectorySeparatorChar & tree_ftp_server.SelectedNode.Text.ToLower & ".xml")

                If IO.File.Exists(_filname) Then

                    IO.File.Delete(_filname)

                    UpdateFTPServers()

                End If

            End If

        End If

    End Sub

    Private Sub FTPServerBearbeitenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FTPServerBearbeitenToolStripMenuItem.Click, BearbeitenToolStripMenuItem1.Click

        Dim _ftp_server As New ConnectionInfo
        Dim _filname As String

        _filname = IO.Path.Combine(Application.StartupPath, "FTPServer" & IO.Path.DirectorySeparatorChar & tree_ftp_server.SelectedNode.Text.ToLower & ".xml")

        If IO.File.Exists(_filname) Then

            _ftp_server = _tools.XMLDeSerialize(_ftp_server, _filname)

            frm_ftp_server.SetMod = True
            frm_ftp_server.SetFTPServer = _ftp_server
            frm_ftp_server.ShowDialog()
            frm_ftp_server.Dispose()

        End If

    End Sub

    Private Sub VerbindenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerbindenToolStripMenuItem.Click, tree_ftp_server.DoubleClick

        Dim _filname As String

        _ftp_client = New FTP.FTP.FtpClient
        _ftp_server = New ConnectionInfo

        If _ftp_client.IsConnected Then
            _ftp_client.Abort()
            _ftp_client.Close()
            _ftp_client.Dispose()
        End If

        lv_sfdl_container.Items.Clear()

        _filname = IO.Path.Combine(Application.StartupPath, "FTPServer" & IO.Path.DirectorySeparatorChar & tree_ftp_server.SelectedNode.Text.ToLower & ".xml")

        If IO.File.Exists(_filname) Then

            _ftp_server = _tools.XMLDeSerialize(_ftp_server, _filname)

            _ftp_client.Host = _ftp_server.GetSetHost
            _ftp_client.Port = _ftp_server.GetSetPort
            _ftp_client.FileTransferType = _ftp_server.GetSetTransferType
            _ftp_client.DataTransferMode = _ftp_server.GetSetTransferMode
            _ftp_client.CharacterEncoding = _tools.ConvertEncodingEnumToEncoding(_ftp_server.GetSetCharacterEncoding)
            _ftp_client.SecurityProtocol = _ftp_server.GetSetSecurityProtocol

            _ftp_client.IsLoggingOn = True

            UpdateFTPLog("Stelle verbindung zum Server her....", Enums.ResponseType.Client)

            'Lock Control while connecting
            tree_ftp_server.Enabled = False
            QuickConnectToolStripMenuItem.Enabled = False

            ConnectFTPServer(_ftp_client, _ftp_server.GetSetAuthRequired, _ftp_server.GetSetUsername, _ftp_server.GetSetPassword)

        End If

    End Sub

    Private Sub _ftp_client_client_request_event(sender As Object, e As FTP.FTP.FtpRequestEventArgs)
        UpdateFTPLog(e.Request.Text, Enums.ResponseType.Client)
    End Sub

    Private Sub _ftp_client_server_respone_event(sender As Object, e As FTP.FTP.FtpResponseEventArgs)
        UpdateFTPLog(e.Response.Text, Enums.ResponseType.Server)
    End Sub

    Private Sub lv_ftp_server_items_DoubleClick(sender As Object, e As EventArgs) Handles lv_ftp_server_items.DoubleClick

        If Not lv_ftp_server_items.SelectedItems.Count = 0 Then

            Try

                If lv_ftp_server_items.SelectedItems.Count = 1 Then

                    Dim _item As New ListViewItem

                    _item = lv_ftp_server_items.SelectedItems(0)

                    If _item.Text = ".." Then

                        Dim _path_one_up As String = String.Empty

                        _path_one_up = txt_current_ftp_path.Text

                        If _path_one_up.Contains("/") Then

                            If _path_one_up.EndsWith("/") Then
                                _path_one_up = _path_one_up.Remove(0, 1)
                            End If

                            _path_one_up = _path_one_up.Remove(_path_one_up.LastIndexOf("/"))


                            If String.IsNullOrEmpty(_path_one_up) Then
                                _path_one_up = "/"
                            End If

                        Else

                            If _path_one_up.EndsWith("\") Then
                                _path_one_up = _path_one_up.Remove(0, 1)
                            End If

                            _path_one_up = _path_one_up.Remove(_path_one_up.LastIndexOf("\"))


                            If String.IsNullOrEmpty(_path_one_up) Then
                                _path_one_up = "\"
                            End If

                        End If


                        If _ftp_server.GetSetUseSpecialCharacterFix Then
                            _path_one_up = _path_one_up.Replace("ÿ", "ÿÿ")
                        End If

                        _ftp_client.ChangeDirectory(_path_one_up)
                        bgw_get_dir_list.RunWorkerAsync()

                    Else

                        Dim _path As String = String.Empty

                        If _item.StateImageIndex = 0 Then

                            _path = _item.SubItems(4).Text.ToString

                            If _ftp_server.GetSetUseSpecialCharacterFix Then
                                _path = _path.Replace("ÿ", "ÿÿ")
                            End If

                            Dim _dir_list As New FTP.FTP.FtpItemCollection

                            _ftp_client.ChangeDirectory(_path)

                            bgw_get_dir_list.RunWorkerAsync()

                        End If

                    End If

                End If

            Catch ex As Exception
            End Try


        End If


    End Sub

    Private Sub bgw_get_dir_list_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgw_get_dir_list.DoWork

        Dim _dir As String = String.Empty
        Dim _dir_list As New FTP.FTP.FtpItemCollection

        ClearFTPItemList()

        If Not e.Argument Is Nothing Then
            _dir = e.Argument.ToString
        End If

        Try

            UpdateCurrentFTPDir(_ftp_client.GetWorkingDirectory)

            Dim _change_dir_up_item As New ListViewItem

            _change_dir_up_item.Text = ".."
            _change_dir_up_item.StateImageIndex = 2

            AddListViewItem(_change_dir_up_item)

            _dir_list = _ftp_client.GetDirList()

            For Each _item In _dir_list

                Dim _lv_item As New ListViewItem

                _lv_item.UseItemStyleForSubItems = True

                Select Case _item.ItemType

                    Case FTP.FTP.FtpItemType.Directory

                        _lv_item.StateImageIndex = 0

                    Case FTP.FTP.FtpItemType.File

                        _lv_item.StateImageIndex = 1

                End Select

                _lv_item.Text = _item.Name
                _lv_item.SubItems.Add(_item.Size.ToString)
                _lv_item.SubItems.Add(_item.Modified)
                _lv_item.SubItems.Add(_item.Attributes)
                _lv_item.SubItems.Add(_item.FullPath)


                AddListViewItem(_lv_item)

            Next


        Catch ex As Exception
            bgw_get_dir_list.ReportProgress(0, ex)
        End Try

    End Sub

    Private Sub bgw_get_dir_list_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw_get_dir_list.ProgressChanged

        If e.ProgressPercentage = 0 Then

            Dim _ex As Exception = e.UserState

            MessageBox.Show(_ex.Message, "Fehler beim lesen der Verzeichnisse!", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End If

    End Sub

    Private Sub ZuSFDLContainerHinzufügenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ZuSFDLContainerHinzufügenToolStripMenuItem.Click

        Try

            Dim _path As String = String.Empty

            For Each _item As ListViewItem In lv_ftp_server_items.SelectedItems

                'Wenn es eine Datei ist
                If _item.StateImageIndex = 1 Then

                    Dim _lv_item As New ListViewItem

                    _path = _item.SubItems(4).Text.ToString

                    If _ftp_server.GetSetUseSpecialCharacterFix Then
                        _path = _path.Replace("ÿ", "ÿÿ")

                        If lv_sfdl_container.Items.Count = 0 Then
                            lbl_directory_root.Text = txt_current_ftp_path.Text.Replace("ÿ", "ÿÿ")
                        End If
                    Else
                        If lv_sfdl_container.Items.Count = 0 Then
                            lbl_directory_root.Text = txt_current_ftp_path.Text
                        End If
                    End If

                    _lv_item.Text = _path
                    _lv_item.SubItems.Add(_item.SubItems(1).Text.ToString)
                    'MD5 Hash Spalte
                    _lv_item.SubItems.Add(String.Empty)
                    lv_sfdl_container.Items.Add(_lv_item)

                End If

                'Ordner
                If _item.StateImageIndex = 0 Then

                    _path = _item.SubItems(4).Text.ToString

                    If _ftp_server.GetSetUseSpecialCharacterFix Then
                        _path = _path.Replace("ÿ", "ÿÿ")
                    End If

                    If lv_sfdl_container.Items.Count = 0 Then
                        lbl_directory_root.Text = _path
                    End If

                    _ftp_client.ChangeDirectory(_path)

                    For Each _file_item In _ftp_client.GetDirListDeep(_path)

                        Try

                            If _file_item.ItemType = FTP.FTP.FtpItemType.File Then

                                Dim _lv_item As New ListViewItem

                                _lv_item.Text = _file_item.FullPath
                                _lv_item.SubItems.Add(_file_item.Size)
                                _lv_item.SubItems.Add(String.Empty)

                                lv_sfdl_container.Items.Add(_lv_item)

                            End If


                        Catch ex As Exception

                        End Try

                    Next

                End If

            Next


        Catch ex As Exception

        End Try


    End Sub


    Private Sub DateiEntfernenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiEntfernenToolStripMenuItem.Click

        For Each _item In lv_sfdl_container.SelectedItems
            lv_sfdl_container.Items.Remove(_item)
        Next

    End Sub

    Private Sub SFDLDateiErstellenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SFDLDateiErstellenToolStripMenuItem.Click

        Dim _sfdl_file As New SFDL_File
        Dim _list_files As New List(Of FileInfo)

        Try

            If lv_sfdl_container.Items.Count = 0 Then
                Throw New Exception("Du musst erst Dateien zum SFDL Container hinzufügen bevor du eine Datei erstellen kannst!")
            End If

            _sfdl_file.GetSetConnectionInfo.GetSetHost = _ftp_server.GetSetHost
            _sfdl_file.GetSetConnectionInfo.GetSetAuthRequired = _ftp_server.GetSetAuthRequired
            _sfdl_file.GetSetConnectionInfo.GetSetCharacterEncoding = _ftp_server.GetSetCharacterEncoding
            _sfdl_file.GetSetConnectionInfo.GetSetName = _ftp_server.GetSetName
            _sfdl_file.GetSetConnectionInfo.GetSetPassword = _ftp_server.GetSetPassword
            _sfdl_file.GetSetConnectionInfo.GetSetPath = _ftp_server.GetSetPath
            _sfdl_file.GetSetConnectionInfo.GetSetPort = _ftp_server.GetSetPort
            _sfdl_file.GetSetConnectionInfo.GetSetSecurityProtocol = _ftp_server.GetSetSecurityProtocol
            _sfdl_file.GetSetConnectionInfo.GetSetTransferMode = _ftp_server.GetSetTransferMode
            _sfdl_file.GetSetConnectionInfo.GetSetTransferType = _ftp_server.GetSetTransferType
            _sfdl_file.GetSetConnectionInfo.GetSetUsername = _ftp_server.GetSetUsername
            _sfdl_file.GetSetConnectionInfo.GetSetUseSpecialCharacterFix = _ftp_server.GetSetUseSpecialCharacterFix

            If _sfdl_file.GetSetConnectionInfo.GetSetName Is Nothing Then
                _sfdl_file.GetSetConnectionInfo.GetSetName = "QuickConnect"
            End If

            For Each _item As ListViewItem In lv_sfdl_container.Items

                Dim _file_info As New FileInfo

                _file_info.GetSetFileFullPath = _item.Text
                _file_info.GetSetFileName = IO.Path.GetFileName(_item.Text)
                _file_info.GetSetDirectoryPath = _file_info.GetSetFileFullPath.Replace(_file_info.GetSetFileName, "").ToString
                _file_info.GetSetDirectoryRoot = lbl_directory_root.Text
                _file_info.GetSetFileSize = _item.SubItems(1).Text.ToString
                _file_info.GetSetMD5FileHash = _item.SubItems(2).Text.ToString

                _list_files.Add(_file_info)

            Next

            _sfdl_file.GetSetFileInfoList = _list_files

            frm_create_sfdl.SFDLFile = _sfdl_file

            frm_create_sfdl.ShowDialog()
            frm_create_sfdl.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try


    End Sub

    Private Sub ExtrasToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExtrasToolStripMenuItem.Click

        If lv_sfdl_container.Items.Count = 0 Then
            SFDLDateiErstellenToolStripMenuItem.Enabled = False
        Else
            SFDLDateiErstellenToolStripMenuItem.Enabled = True
        End If

    End Sub

    Private Sub MD5HashHinzufügenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MD5HashHinzufügenToolStripMenuItem.Click

        If Not lv_sfdl_container.SelectedItems.Count = 0 Then
            frm_add_md5.GetSetItem = lv_sfdl_container.SelectedItems(0).Text
            frm_add_md5.ShowDialog()
            frm_add_md5.Dispose()
        End If

    End Sub

    Private Sub VerbindungTrennenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerbindungTrennenToolStripMenuItem.Click

        If _ftp_client.IsConnected Then
            _ftp_client.Close()
            _ftp_client.Dispose()
        End If

        lv_ftp_server_items.Items.Clear()
        _tools.ClearSFDLQueue()

    End Sub

    Private Sub cmd_change_dir_Click(sender As Object, e As EventArgs) Handles cmd_change_dir.Click

        If _ftp_client.IsConnected Then

            Try

                If _ftp_server.GetSetUseSpecialCharacterFix Then
                    txt_current_ftp_path.Text = txt_current_ftp_path.Text.Replace("ÿ", "ÿÿ")
                End If

                _ftp_client.ChangeDirectory(txt_current_ftp_path.Text)
                bgw_get_dir_list.RunWorkerAsync()

            Catch ex As Exception

            End Try

        End If

    End Sub

    Private Sub BenutzerdefiniertenFTPBefehlSendenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BenutzerdefiniertenFTPBefehlSendenToolStripMenuItem.Click

        Try
            _ftp_client.Quote(InputBox("Bitte FTP-Befehl eingeben:", "Benutzerdefinierter Befehl"))

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Custom Command Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub

    Private Sub LeerenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LeerenToolStripMenuItem.Click

        If MessageBox.Show("Alle Einträge entfernen?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            _tools.ClearSFDLQueue()
        End If

    End Sub

    Private Sub lbl_directory_root_Click(sender As Object, e As EventArgs) Handles lbl_directory_root.Click
        lbl_directory_root.Text = InputBox("Pfad eingeben:")
    End Sub

    Private Sub UmbennenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UmbennenToolStripMenuItem.Click

        Dim _ftp_server As New ConnectionInfo
        Dim _filname As String
        Dim _new_name As String

        Try

            _filname = IO.Path.Combine(Application.StartupPath, "FTPServer" & IO.Path.DirectorySeparatorChar & tree_ftp_server.SelectedNode.Text.ToLower & ".xml")

            If IO.File.Exists(_filname) Then

                _ftp_server = _tools.XMLDeSerialize(_ftp_server, _filname)

                _new_name = InputBox("Neuer Name:", "Umbennen", _ftp_server.GetSetName)

                If String.IsNullOrEmpty(_new_name) Then
                    Throw New Exception("Neuer Name darf nicht leer sein!")
                End If

                _ftp_server.GetSetName = _new_name

                _tools.XMLSerialize(_ftp_server, IO.Path.Combine(Application.StartupPath, "FTPServer" & IO.Path.DirectorySeparatorChar & _ftp_server.GetSetName.ToLower & ".xml"))

                IO.File.Delete(_filname)

                UpdateFTPServers()


            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "So Nicht", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try

    End Sub

    Private Sub EinstellungenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EinstellungenToolStripMenuItem.Click

        frm_settings.ShowDialog()

        frm_settings.Dispose()


    End Sub

    Private Sub ConnectFTPServer(ByVal _ftp_client As FTP.FTP.FtpClient, ByVal _auth_required As Boolean, Optional ByVal _username As String = "anonymous", Optional _password As String = "")

        'Add Event Handlers
        AddHandler _ftp_client.OpenAsyncCompleted, AddressOf _ftp_client_open_async_event
        AddHandler _ftp_client.ServerResponse, AddressOf _ftp_client_server_respone_event
        AddHandler _ftp_client.ClientRequest, AddressOf _ftp_client_client_request_event
        AddHandler _ftp_client.ValidateServerCertificate, AddressOf _ftp_client_cert_validate

        If _auth_required Then
            _ftp_client.OpenAsync(_username, _password)
        Else
            _ftp_client.OpenAsync("anonymous", "password")
        End If


    End Sub

    Private Sub ActiveModusToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ActiveModusToolStripMenuItem.Click

        Dim _clipboard_text As String = String.Empty

        _ftp_client = New FTP.FTP.FtpClient
        _ftp_server = New ConnectionInfo


        Try

            If My.Computer.Clipboard.ContainsText Then
                _clipboard_text = My.Computer.Clipboard.GetText
            End If

            If _clipboard_text.StartsWith("ftp://") Then
                _ftp_server = _tools.ParseFTPConnectionString(_clipboard_text)
            Else
                Throw New Exception("Es wurde kein gültiger FTP Connection String gefunden!")
            End If

            _ftp_client.Host = _ftp_server.GetSetHost
            _ftp_client.Port = _ftp_server.GetSetPort
            _ftp_client.FileTransferType = FTP.FTP.TransferType.Binary
            _ftp_client.DataTransferMode = FTP.FTP.TransferMode.Active
            ' _ftp_client.CharacterEncoding = System.Text.Encoding.Default

            _ftp_server.GetSetSecurityProtocol = FTP.FTP.FtpSecurityProtocol.None
            _ftp_server.GetSetTransferMode = FTP.FTP.TransferMode.Active
            _ftp_server.GetSetTransferType = FTP.FTP.TransferType.Binary
            _ftp_server.GetSetUseSpecialCharacterFix = False

            _ftp_client.IsLoggingOn = True

            ConnectFTPServer(_ftp_client, _ftp_server.GetSetAuthRequired, _ftp_server.GetSetUsername, _ftp_server.GetSetPassword)

        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub

    Private Sub PassiveModusToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PassiveModusToolStripMenuItem.Click

        Dim _clipboard_text As String = String.Empty

        _ftp_client = New FTP.FTP.FtpClient
        _ftp_server = New ConnectionInfo


        Try

            If My.Computer.Clipboard.ContainsText Then
                _clipboard_text = My.Computer.Clipboard.GetText
            End If

            If _clipboard_text.StartsWith("ftp://") Then
                _ftp_server = _tools.ParseFTPConnectionString(_clipboard_text)
            Else
                Throw New Exception("Es wurde kein gültiger FTP Connection String gefunden!")
            End If

            _ftp_client.Host = _ftp_server.GetSetHost
            _ftp_client.Port = _ftp_server.GetSetPort
            _ftp_client.FileTransferType = FTP.FTP.TransferType.Binary
            _ftp_client.DataTransferMode = FTP.FTP.TransferMode.Passive
            ' _ftp_client.CharacterEncoding = System.Text.Encoding.Default

            _ftp_server.GetSetSecurityProtocol = FTP.FTP.FtpSecurityProtocol.None
            _ftp_server.GetSetTransferMode = FTP.FTP.TransferMode.Passive
            _ftp_server.GetSetTransferType = FTP.FTP.TransferType.Binary
            _ftp_server.GetSetUseSpecialCharacterFix = False

            _ftp_client.IsLoggingOn = True

            ConnectFTPServer(_ftp_client, _ftp_server.GetSetAuthRequired, _ftp_server.GetSetUsername, _ftp_server.GetSetPassword)

        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub

    Private Sub ÜberSFDLNETCreatorToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ÜberSFDLNETCreatorToolStripMenuItem.Click
        AboutBox.ShowDialog()
    End Sub

    Private Sub FTPServerPrüfenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FTPServerPrüfenToolStripMenuItem.Click

        Dim _ftp_server_list As New List(Of ConnectionInfo)

        If MessageBox.Show("Willst du wirklich alle FTP Server auf ihre Verfügbarkeit prüfen?", "FTP Server prüfen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

            'Lock Control while connecting
            tree_ftp_server.Enabled = False
            QuickConnectToolStripMenuItem.Enabled = False

            For Each _item As TreeNode In tree_ftp_server.Nodes(0).Nodes

                Dim _filename As String = String.Empty
                Dim _ftp_server As New ConnectionInfo

                _filename = IO.Path.Combine(Application.StartupPath, "FTPServer" & IO.Path.DirectorySeparatorChar & _item.Text.ToLower & ".xml")

                If IO.File.Exists(_filename) Then

                    _ftp_server = _tools.XMLDeSerialize(_ftp_server, _filename)
                    _ftp_server_list.Add(_ftp_server)

                End If

            Next

            rtb_log.Clear()

            If _ftp_server_list.Count = 0 Then
                UpdateFTPLog("Keine FTP Server zum prüfen gefunden...", Enums.ResponseType.Client)
            Else
                UpdateFTPLog("Prüfe FTP Server...bitte warten...", Enums.ResponseType.Client)

                bgw_checkftp_server.RunWorkerAsync(_ftp_server_list)
            End If

        End If

    End Sub

    Private Sub bgw_checkftp_server_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgw_checkftp_server.DoWork

        Dim _ftp_server_list As New List(Of ConnectionInfo)

        _ftp_server_list = e.Argument

        For Each _ftp_server As ConnectionInfo In _ftp_server_list

            Dim _ftp_client As New FTP.FTP.FtpClient
            Dim _check_progress_info As New bgw_ftp_server_progress_info

            Try

                _check_progress_info.FTPServerName = _ftp_server.GetSetName

                UpdateFTPLog("Teste Server " & _ftp_server.GetSetName, Enums.ResponseType.Client)

                _ftp_client.Host = _ftp_server.GetSetHost
                _ftp_client.Port = _ftp_server.GetSetPort
                _ftp_client.FileTransferType = _ftp_server.GetSetTransferType
                _ftp_client.DataTransferMode = _ftp_server.GetSetTransferMode
                ' _ftp_client.CharacterEncoding = _tools.ConvertEncodingEnumToEncoding(_ftp_server.GetSetCharacterEncoding)
                _ftp_client.CommandTimeout = 500
                _ftp_client.TcpTimeout = 500
                _ftp_client.TransferTimeout = 500

                _ftp_client.IsLoggingOn = False

                If String.IsNullOrEmpty(_ftp_server.GetSetUsername) Then
                    _ftp_server.GetSetUsername = "anonymous"
                End If

                If String.IsNullOrEmpty(_ftp_server.GetSetPassword) Then
                    _ftp_server.GetSetPassword = "password"
                End If

                _ftp_client.Open(_ftp_server.GetSetUsername, _ftp_server.GetSetPassword)

                UpdateFTPLog("Verbindung zum Server " & _ftp_server.GetSetName & " erfolgreich hergestellt!", Enums.ResponseType.Client)

                If Not String.IsNullOrEmpty(_ftp_server.GetSetPath) Then
                    _ftp_client.ChangeDirectory(_ftp_server.GetSetPath)
                    UpdateFTPLog("Verzeichnis wechsel erfolgreich!", Enums.ResponseType.Client)
                End If

                _check_progress_info.FTPServerStatus = State.OK

            Catch ex As Exception

                If ex.Message.StartsWith("Could not change working directory to") Then
                    _check_progress_info.FTPServerStatus = State.Warnung
                    UpdateFTPLog("Verzeichnis konnte nicht gewechselt werden!", Enums.ResponseType.Client)
                Else
                    _check_progress_info.FTPServerStatus = State.Fehler
                    UpdateFTPLog("Verbindung zum Server konnte nicht hergestellt werden!", Enums.ResponseType.Client)
                End If

            Finally

                If _ftp_client.IsConnected Then
                    _ftp_client.Dispose()
                End If

                bgw_checkftp_server.ReportProgress(0, _check_progress_info)
            End Try

        Next

        UpdateFTPLog("FTP Server Check abgeschlossen!", Enums.ResponseType.Client)


    End Sub

    Private Sub bgw_checkftp_server_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw_checkftp_server.ProgressChanged

        Dim _progress_info As New bgw_ftp_server_progress_info

        _progress_info = e.UserState

        For Each _item As TreeNode In tree_ftp_server.Nodes(0).Nodes

            If _item.Text.Equals(_progress_info.FTPServerName) Then

                Select Case _progress_info.FTPServerStatus

                    Case State.OK

                        _item.ImageIndex = 4

                    Case State.Warnung

                        _item.ImageIndex = 5


                    Case State.Fehler

                        _item.ImageIndex = 6

                End Select

            End If

        Next

    End Sub

    Private Sub bgw_checkftp_server_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw_checkftp_server.RunWorkerCompleted

        tree_ftp_server.ExpandAll()

        'Lock Control while connecting
        tree_ftp_server.Enabled = True
        QuickConnectToolStripMenuItem.Enabled = True

    End Sub

    Private Sub _ftp_client_cert_validate(sender As Object, e As FTP.FTP.ValidateServerCertificateEventArgs)

        e.IsCertificateValid = True

    End Sub

End Class
